package biz

import (
	"server/base/db"
	"server/biz/proto"
)

// 获取第一个就绪的订单ID
func GetReadyOrder(bot_id string) int {
	var id int
	db.Replica.Get(&id, `select id from orders where status=1 and bot_id=? order by seq desc, id desc limit 1`,
		bot_id)
	return id
}

func TakeInflightOrder(bot_id string) int {
	tx := db.Primary.Begin()
	defer tx.Rollback()
	var id int
	tx.Get(&id, `select id from orders 
where status=2 and bot_id="" order by seq desc, id desc limit 1`)
	if id != 0 {
		tx.Exec(`update orders set bot_id=? where id=?`, bot_id, id)
	}
	tx.Commit()
	return id
}

// 获取第一个进行中的订单ID
func GetInflightOrder(bot_id string) int {
	var id int
	db.Replica.Get(&id, `select id from orders 
where status=2 and bot_id=? order by seq desc, id desc limit 1`, bot_id)
	//if id == 0 {
	//	id = TakeInflightOrder(bot_id)
	//}
	return id
}

func AskTask(bot_id string) *proto.Task {
	order_id := GetInflightOrder(bot_id)
	if order_id == 0 {
		return nil
	}
	order := GetOrder(order_id)
	if order == nil {
		return nil
	}
	if order.Status != 2 {
		return nil
	}
	op := PopOrderPkg(order_id)
	if op == nil {
		return nil
	}
	//pkg := GetPackage(op.PkgId)
	//if pkg == nil {
	//	// BUG: 有pkg_id但是没包, 标记为"没找到"
	//	FinTask(op.Id, "pkg not found")
	//	//SetOrderPkgStatus(op.Id, 2)
	//	return nil
	//}
	out := &proto.Task{
		Id:       op.Id,
		OrderId:  op.OrderId,
		Src:      op.PkgSrc,
		Dst:      order.Dst,
		Size:     op.PkgSize,
		Progress: order.Progress + 1,
		Total:    order.Total,
	}
	return out
}

func IsFinished(tx *db.MustTx, order_id int) bool {
	var rest int
	tx.Get(&rest, `select count(*) from order_pkg where order_id=? and status=0`, order_id)
	return rest == 0
}

// 订单中有问题的任务数
func IssueTasks(tx *db.MustTx, order_id int) int {
	var n int
	tx.Get(&n, `select count(*) from order_pkg where order_id=? and status=2`, order_id)
	return n
}

func OrderProgress(tx *db.MustTx, order_id int) int {
	var n int
	tx.Get(&n, `select count(*) from order_pkg where order_id=? and status=1`, order_id)
	return n
}

type FinResult struct {
	Finish  bool   `json:"finish"`   // 整个订单是否拷贝完成
	OrderNo string `json:"order_no"` // 订单号
	OrderId int    `json:"order_id"` // 订单ID
}

func FinTask(id int, error string) *FinResult {
	op := GetOrderPkg(id)
	if op == nil {
		return nil
	}
	if op.OrderId == 0 {
		return nil
	}
	tx := db.Primary.Begin()
	defer tx.Rollback()
	var fin bool
	if error != "" {
		tx.Exec(`update order_pkg set status=2 where id=?`, id)
		//tx.Exec(`update orders set status=3, error=? where id=?`, error, op.OrderId)
	} else {
		tx.Exec(`update order_pkg set status=1 where id=?`, id)
		n := OrderProgress(tx, op.OrderId)
		tx.Exec(`update orders set progress=? where id=?`, n, op.OrderId)
	}
	fin = IsFinished(tx, op.OrderId)
	if fin {
		status := 4
		if IssueTasks(tx, op.OrderId) > 0 {
			status = 3
		}
		tx.Exec(`update orders set status=? where id=?`, status, op.OrderId)
	}
	tx.Commit()
	// 自动开始下一个订单
	var old *OrderRaw
	if fin {
		old = GetOrder(op.OrderId)
		if old != nil {
			next_id := GetReadyOrder(old.BotId)
			if next_id != 0 {
				db.Primary.Exec(`update orders set status=2 where id=? and status=1 order by id asc`,
					next_id)
			}
		}
	}
	out := &FinResult{
		Finish:  fin,
		OrderId: op.OrderId,
	}
	if old != nil {
		out.OrderNo = old.No
	}
	return out
}
